package com.zjh.admin.controller;


import com.zjh.admin.entity.VO.OnlineSysUserVO;
import com.zjh.admin.service.LoginService;
import com.zjh.admin.service.impl.UserOnlineService;
import com.zjh.admin.vo.LoginVO;
import com.zjh.admin.websocket.servive.WebSocketMessageService;
import com.zjh.common.entity.LoginUser;
import com.zjh.common.entity.Response;
import com.zjh.common.exception.ServiceException;
import com.zjh.common.utils.RequestContext;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Set;


@RestController
@RequestMapping("/Admin/account")
@CrossOrigin(origins = "http://localhost:5173")
public class LoginController {

    @Resource
    private LoginService loginService;

    @Resource
    private WebSocketMessageService webSocketMessageService;

    @Resource
    private UserOnlineService userOnlineService;

    @CrossOrigin
    @PostMapping("/login")
    public Response<HashMap<String, Object>> login(@RequestBody LoginVO loginVO) throws Exception {
        LoginUser login = loginService.login(loginVO.getUsername(), loginVO.getPassword());
        if (login == null) {
            return Response.error("认证失败");
        }

        HashMap<String, Object> res = new HashMap<>();
        res.put("roleId", login.getRoleId());
        res.put("username", login.getUsername());
        res.put("nickname", login.getNickname());
        res.put("userId", login.getUserId());
        res.put("token", login.getJwt());

        webSocketMessageService.pushLoginMsgToAllOnlineUser(login);
        return Response.success(res);
    }

    @PostMapping("/logout")
    public Response logout() {

        //清除SpringSecurity上下文
        SecurityContextHolder.clearContext();

        return Response.success();
    }


    @GetMapping("/testActive/add")
    public Response<?> getDailyActiveUsers(
            @RequestParam @DateTimeFormat(pattern = "yyyyMMdd") LocalDate date) {

        LoginUser loginUser = RequestContext.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前登陆用户为空");
        }
        // 记录活跃用户
        userOnlineService.userLogin(loginUser, date);

        return Response.success();
    }

    /**
     * 获取某日所有在线用户列表
     *
     * @param date 查询日期
     * @return 用户ID集合
     */
    @GetMapping("/testActive/getOneDay")
    public Response<Set<OnlineSysUserVO>> getDailyOnlineUsers(
            @RequestParam @DateTimeFormat(pattern = "yyyyMMdd") LocalDate date) {

        Set<OnlineSysUserVO> res = userOnlineService.getDailyOnlineUsers(date);

        return Response.success(res);
    }

    @PostMapping("/hello")
    public String hello() {

        return "hello";
    }
}
